package com.runfast.paotui.mq;

import com.runfast.paotui.dao.model.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.ContentTypeDelegatingMessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import sun.java2d.pipe.SpanShapeRenderer;

import java.util.Date;
import java.util.UUID;

/**
 * @author: lijin
 * @date: 2018年04月18日
 */

@Slf4j
@Component
public class AmqpClient {
    private final AmqpAdmin amqpAdmin;
    private final AmqpTemplate amqpTemplate;
    @Autowired
    public AmqpClient(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
        this.amqpAdmin = amqpAdmin;
        this.amqpTemplate = amqpTemplate;
    }

    @Async
    public void publish(Object object){
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setMessageId(UUID.randomUUID().toString());
        messageProperties.setTimestamp(new Date());

        SimpleMessageConverter simpleMessageConverter = new SimpleMessageConverter();
        Message message = simpleMessageConverter.toMessage(object, messageProperties);
        amqpTemplate.send("user_order_exchange","",message);

    }


    @RabbitListener(queues = "user_order_manager" )
    public void processMessage1(Message message) {
        MessageProperties messageProperties = message.getMessageProperties();
        SimpleMessageConverter simpleMessageConverter = new SimpleMessageConverter();
        Order order = (Order) simpleMessageConverter.fromMessage(message);

        log.info("manager---- msgId: "+messageProperties.getMessageId()+", time: "+messageProperties.getTimestamp()+" body: "+order.getId()+" "+order.getStatus());

    }

    @RabbitListener(queues = "user_order_business" )
    public void processMessage2(Message message) {
        MessageProperties messageProperties = message.getMessageProperties();
        SimpleMessageConverter simpleMessageConverter = new SimpleMessageConverter();
        Order order = (Order) simpleMessageConverter.fromMessage(message);

        log.info("business---- msgId: "+messageProperties.getMessageId()+", time: "+messageProperties.getTimestamp()+" body: "+order.getId()+" "+order.getStatus());

    }


}
